from ruamel import yaml
from common.settings import logger
from typing import Dict
from utils.otherUtils.file_control import check_file_path
from common.constant import ApiInfo


class YamlHandler:

    def __init__(self, config_file_path: str = None, api_file_path: str = None, project_name: str = None,
                 api_name: str = None):
        self.config_file_path = config_file_path
        self.api_file_path = api_file_path
        self.project_name = project_name
        self.api_name = api_name
        self.config_info = {}

    @staticmethod
    def read_yaml_file(file_path: str) -> Dict:
        with open(file_path, 'r', encoding='utf-8') as file:
            return yaml.load(file, Loader=yaml.RoundTripLoader)

    def get_config_info(self) -> None:
        self.config_file_path = check_file_path(self.config_file_path)
        config_info = self.read_yaml_file(self.config_file_path)
        if self.project_name:
            if self.project_name not in config_info.keys():
                raise ValueError(f'{self.project_name}不存在')
            self.config_info = config_info[self.project_name]
        else:
            raise ValueError('缺少project_name')

    def get_api_info(self) -> Dict:
        self.api_file_path = check_file_path(self.api_file_path)
        all_api_info = self.read_yaml_file(self.api_file_path)
        if self.api_name:
            if self.api_name not in all_api_info.keys():
                logger.error(f'{self.api_name}不存在')
            if self.config_info:
                host = self.config_info.get(ApiInfo.HOST.value)
                cookie = self.config_info.get(ApiInfo.COOKIE.value)
                if host and cookie:
                    all_api_info[self.api_name][ApiInfo.HOST.value] = host
                    all_api_info[self.api_name][ApiInfo.HEADERS.value][ApiInfo.COOKIE.value] = cookie
                    return all_api_info[self.api_name]
                else:
                    raise ValueError('host或cookie为空')
            else:
                raise ValueError('未获取到配置信息')
        else:
            raise ValueError('缺少api_name')

    def run(self) -> Dict:
        self.get_config_info()
        return self.get_api_info()


if __name__ == '__main__':
    obj = YamlHandler('common/api_common_info.yaml', 'api_detail/bilibili/account_center.yaml', 'bilibili', 'editAvatar')
    print(obj.run())
